<?php

namespace app\api\controllers;

use yii\web\Controller;
use app\models\GkyQyhSpGoabroad;
use app\api\Response;
use app\api\ApprovalMessage;

class GoabroadController extends Controller {

    public $enableCsrfValidation = false;

    function actionCreate($userId) {
        $params = \Yii::$app->request->post();
        $model = new GkyQyhSpGoabroad();
        $model->proposer_id = $userId;
        $model->approver_id = isset($params['approver_id']) ? $params['approver_id'] : 1;
        $model->reason = isset($params['content']) ? $params['content'] : '';
        $model->place = isset($params['place']) ? $params['place'] : '';
        $model->start_time = isset($params['start_time']) ? $params['start_time'] : '0000-00-00 00:00:00';
        $model->end_time = isset($params['end_time']) ? $params['end_time'] : '0000-00-00 00:00:00';
        $model->create_time = date('Y-m-d H:i:s', time());
        $model->work_unit = isset($params['work_unit']) ? $params['work_unit'] : '';
        $model->print_code = 'GOAB' . rand(1000, 9999) . time();
        $model->status = 0;
        if ($model->save()) {
            Response::setHeader();
            echo 100;
            ApprovalMessage::sendMessage($model->proposer_id, $model->approver_id, 0, '出国');
        } else {
            Response::setHeader();
            echo -100;
        }
    }

    public function actionGetGoabroad($printCode) {
        $result = GkyQyhSpGoabroad::getGoabroad($printCode);
        Response::setHeader();
        echo json_encode($result);
    }

    public function actionAgree($printCode,$opinion) {
        if (GkyQyhSpGoabroad::agreeGoabroad($printCode,$opinion)) {
            Response::setHeader();
            echo 1;
            $model = GkyQyhSpGoabroad::findOne(['print_code' => $printCode]);

            if (\Yii::$app->request->isGet) {
                ApprovalMessage::sendMessage($model->approver_id, $model->proposer_id, 1, '出国', $printCode);
            }
        } else {
            Response::setHeader();
            echo -1;
        }
    }

    public function actionRefuse($printCode,$opinion) {
        if (GkyQyhSpGoabroad::refuseGoabroad($printCode,$opinion)) {
            Response::setHeader();
            $model = GkyQyhSpGoabroad::findOne(['print_code' => $printCode]);
            if (\Yii::$app->request->isGet) {
                ApprovalMessage::sendMessage($model->approver_id, $model->proposer_id, -1, '出国', $printCode);
            }
            echo 1;
        } else {
            Response::setHeader();
            echo -1;
        }
    }

}
